package com.gujiangbo.sentinel.controller;

import com.alibaba.csp.sentinel.Entry;
import com.alibaba.csp.sentinel.SphU;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.RuleConstant;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRule;
import com.alibaba.csp.sentinel.slots.block.flow.FlowRuleManager;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;

@RestController
public class HelloController {

    @GetMapping("sayHello")
    public String sayHello() {
        /**
         * 使用限流规则
         */
        try {
            //限流入口
            Entry hello = SphU.entry("Hello");
            return "hello Sentinel !";
        } catch (BlockException e) {
            e.printStackTrace();
            return "系统繁忙，请稍后重试";//限流或者降级处理
        }

    }

    /**
     * 自定义限流规则
     */
/*    @PostConstruct//当前类的构造函数执行完毕之后再执行的方法
    public void initFlowRules() {
        //1.创建限流规则集合
        List<FlowRule> rules = new ArrayList<FlowRule>();
        //2.创建限流规则
        FlowRule flowRule = new FlowRule();
        //定义资源，标识Sentinel对哪个资源生效
        flowRule.setResource("Hello");
        //定义限流规则类型,QPS
        flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
        //QPS设置限流值,每秒通过的请求个数
        flowRule.setCount(2);
        //3.将限流规则存放到集合中
        rules.add(flowRule);
        //4.加载限流规则
        FlowRuleManager.loadRules(rules);
    }*/
    public static void main(String[] args) {
        HelloController helloController = new HelloController();
        while (true) {
            helloController.sayHello();
        }
    }
}
